<?php

namespace app\api\controller;

use addons\epay\library\Service;
use app\admin\model\course\ClassesConfig;
use app\admin\model\course\Order;
use app\admin\model\course\OrderGoods;
use app\admin\model\course\OrderSign;
use app\admin\model\Third;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\MoneyLog;
use app\common\model\order\PayLog;
use fast\Random;
use think\Config;
use think\Db;
use think\Validate;

/**
 * 老师课程信息接口
 * @ApiWeigh (90)
 */
class TeacherCourse extends Api
{
    protected $noNeedLogin = [];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();


    }



    /**
     * 课程表
     *
     * @ApiMethod (POST)
     * @ApiWeigh (100)
     * @ApiParams   (name="day", type="string", required=true, description="日期2023-01-01")
     */
    public function courseList()
    {
        $day = $this->request->post('day');
        $orderGoodsModel = new OrderGoods();
        $condition = [
            "order_goods.teacher_id" => $this->auth->id,
        ];
        $list = $orderGoodsModel->getTimeTable($condition, $day,1, [Order::STATUS_PAY,Order::STATUS_SUCCESS]);

        $this->success("",$list);
    }


    /**
     * 学员列表/成长总结
     *
     * @ApiMethod (POST)
     * @ApiWeigh (99)
     * @ApiParams   (name="day", type="string", required=true, description="日期2023-01-01")
     * @ApiParams   (name="order_goods_id", type="string", required=true, description="课程表id")
     * @ApiReturnParams   (name="status", type="int", required=true, description="0:待签到；1：签到；2:请假;3:活动")
     */
    public function studentList()
    {
        $day = $this->request->post('day');
        $order_goods_id = $this->request->post('order_goods_id');
        $orderGoodsModel = new OrderGoods();
        try {
            $studentList = $orderGoodsModel->getStudentList([],$order_goods_id);

            //leaveList 请假人员
            $orderGoodsCondition = [
                "order_goods.id" => $order_goods_id,
            ];
            $orderGoods = $orderGoodsModel->getTimeTable($orderGoodsCondition,$day,false,[Order::STATUS_PAY,Order::STATUS_SUCCESS]);
            $orderSignModel = new OrderSign();
            $condition = [
//                "order_sign.order_goods_id" => $order_goods_id,
                "order_sign.course_id" => $orderGoods['course_id'],
                "order_sign.school_id" => $orderGoods['school_id'],
                "order_sign.classes_id" => $orderGoods['classes_id'],
                "order_sign.time_no" => $orderGoods['time_no'],
                "order_sign.teacher_id" => $orderGoods['teacher_id'],
                "order_sign.w" => $orderGoods['w'],
                "order_sign.day" => $day,
                "order_sign.status" => ['in',[$orderSignModel::STATUS_SIGN,$orderSignModel::STATUS_ADMIN_SIGN,$orderSignModel::STATUS_LEAVE,$orderSignModel::STATUS_ACTIVITY]],
            ];
//            dump($condition);exit;
            $signList = $orderSignModel->askSignList($condition, false);
            $studentIds = array_keys($signList);


            foreach ($studentList as $key => $value){
                $value['status'] = 0;
                if(in_array($value['student_id'], $studentIds)){
                    $value['status'] = $signList[$value['student_id']];
                }
            }

            //签到日志
            $signLogcondition = [
//                "order_sign.order_goods_id" => $order_goods_id,
                "order_sign.course_id" => $orderGoods['course_id'],
                "order_sign.school_id" => $orderGoods['school_id'],
                "order_sign.classes_id" => $orderGoods['classes_id'],
                "order_sign.time_no" => $orderGoods['time_no'],
                "order_sign.teacher_id" => $orderGoods['teacher_id'],
                "order_sign.w" => $orderGoods['w'],
                "order_sign.status" => ['in',[$orderSignModel::STATUS_SIGN,$orderSignModel::STATUS_ADMIN_SIGN]],
            ];
            $signLog = $orderSignModel->getSignLog($signLogcondition,1);

            //请假人员
            //当前课程的分类
            $leaveList = [];
            $teacher_category_ids = array_filter(explode(",",$this->auth->works_category_id));
            if(count($teacher_category_ids)){
                $courseModel = new \app\admin\model\course\Course();
                $course_ids = $courseModel->where("category_id","in",$teacher_category_ids)->column("id");
//                if(count($course_ids)){
//                    $course_ids = array_diff($course_ids,[$orderGoods['course_id']]);
//                }
                $leaveList = $orderSignModel->with(["student"=>function($query){
                    $query->withField("name");
                }])->where("order_sign.course_id","in",$course_ids)
                    ->where("order_sign.is_buke",0)
                    ->where("order_sign.class_hour",$orderGoods['class_hour'])
                    ->where("order_sign.status",$orderSignModel::STATUS_LEAVE)
                    ->group("school_id,classes_id,w,course_id,time_no")
                    ->select();

            }


        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $res = [
            'studentList' => $studentList,
            'leaveList' => $leaveList,
            'signLog' => $signLog,

        ];
        $this->success("查询成功",$res);
    }


    /**
     * 成长总结详情
     *
     * @ApiMethod (POST)
     * @ApiWeigh (98)
     * @ApiParams   (name="id", type="string", required=true, description="成长总结学员列表id")
     */
    public function xiaojieInfo()
    {
        $id = $this->request->post('id');
        $orderGoodsModel = new OrderGoods();
        try {
            $signLog = $orderGoodsModel->where("id",$id)->field("id,is_xiaojie,xiaojie_image,xiaojie_content")->find();
            if($signLog){
                $signLog['xiaojie_image_arr'] = [];
                if($signLog['xiaojie_image']){
                    $signLog['xiaojie_image_arr'] = explode(",",$signLog['xiaojie_image']);
                }
            }
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("查询成功",$signLog);
    }
    /**
     * 成长总结修改
     *
     * @ApiMethod (POST)
     * @ApiWeigh (97)
     * @ApiParams   (name="id", type="string", required=true, description="成长总结学员列表id")
     * @ApiParams   (name="xiaojie_image", type="string", required=true, description="成长总结图片")
     * @ApiParams   (name="xiaojie_content", type="string", required=true, description="成长总结内容")
     */
    public function xiaojieChange()
    {

        $data = $this->request->post();
        $validate = new Validate([
            ["id","require","请选择学员成长总结"],
            ["xiaojie_image","require","请上传成长总结图片"],
            ["xiaojie_content","require","请上传成长总结内容"],
        ]);
        $result = $validate->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $orderGoodsModel = new OrderGoods();
        try {
            $orderGoods = $orderGoodsModel->get($data['id']);
            $data['is_xiaojie'] = 1;
            $orderGoods->save($data);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("填写成功");
    }

    /**
     * 签到
     *
     * @ApiMethod (POST)
     * @ApiWeigh (95)
     * @ApiParams   (name="order_goods_id", type="string", required=true, description="课程表id")
     * @ApiParams   (name="day", type="string", required=true, description="日期2023-01-01")
     * @ApiParams   (name="student_ids", type="string", required=true, description="学员列表数组[1,2,3,4]")
     * @ApiParams   (name="leave_student_ids", type="string", required=true, description="学员列表数组[1,2,3]")
     */
    public function courseSign()
    {
        $order_goods_id = $this->request->post('order_goods_id');
        $student_ids = $this->request->post('student_ids/a');
        $leave_student_ids = $this->request->post('leave_student_ids/a');
//        $student_ids = [16,17];
        $day = $this->request->post('day');
        $orderGoodsModel = new OrderGoods();
        $orderSignModel = new OrderSign();
        Db::startTrans();
        try {
            $condition = [
                "order_goods.id" => $order_goods_id,
            ];
            $orderGoods = $orderGoodsModel->getTimeTable($condition,$day,false);
            $time_no = explode(" ",deal_time_text($orderGoods['time_no']));
            $end_time = strtotime($time_no[1]);
            if(time() > $end_time + 1200){
                exception("签到时间已过");
            }

            $studentCondition = [
                "student_id" => ["in",$student_ids]
            ];
//            dump($studentCondition);exit;
            $studentList = $orderGoodsModel->getStudentList($studentCondition,$order_goods_id);


            $sign_data = [];
            foreach ($studentList as $key => $value){
                if(in_array($value['student_id'],$student_ids)){
                    //检测今天有没有签到
                    $orderGoods['student_id'] = $value['student_id'];
                    $orderGoods['order_id'] = $value['order_id'];
                    $orderGoods['id'] = $value['id'];
                    $sign_data[] = $orderSignModel->sign($orderGoods,$day,$orderSignModel::STATUS_SIGN,"",true);
                }
            }
            //检测下订单是否完成
            $order = new Order();
//            dump($sign_data);exit;
            if(count($sign_data) > 0){
                $orderSignModel->insertAll($sign_data);


                foreach ($sign_data as $key => $value){
                    $order->checkOrderSuccessStatus($value['order_id']);

                }

            }else{
//                exception("请选择学员进行签到");
            }


            //补课的处理
            $orderSignModel->where("id","in",$leave_student_ids)->update([
                "is_buke" => 1,
                "buke_teacher_id" => $this->auth->id,
            ]);
            $leave_order_ids =  $orderSignModel->where("id","in",$leave_student_ids)->column("order_id");
            foreach ($leave_order_ids as $order_id){
                $order->checkOrderSuccessStatus($order_id);
            }
            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success("签到成功");

    }

    /**
     * 签到日志/学习记录
     *
     * @ApiMethod (POST)
     * @ApiWeigh (94)
     * @ApiParams   (name="day", type="string", required=true, description="日期2023-01-01")
     * @ApiParams   (name="order_goods_id", type="string", required=true, description="课程表id")
     */
    public function signLogList()
    {
        $day = $this->request->post('day');
        $order_goods_id = $this->request->post('order_goods_id');
        $orderGoodsModel = new OrderGoods();
        try {

            $orderGoodsCondition = [
                "order_goods.id" => $order_goods_id,
            ];
            $orderGoods = $orderGoodsModel->getTimeTable($orderGoodsCondition,$day,false,[Order::STATUS_PAY,Order::STATUS_SUCCESS]);
            $orderSignModel = new OrderSign();
            //签到日志
            $signLogcondition = [
//                "order_sign.order_goods_id" => $order_goods_id,
                "order_sign.day" => $day,
                "order_sign.course_id" => $orderGoods['course_id'],
                "order_sign.school_id" => $orderGoods['school_id'],
                "order_sign.classes_id" => $orderGoods['classes_id'],
                "order_sign.time_no" => $orderGoods['time_no'],
                "order_sign.teacher_id" => $orderGoods['teacher_id'],
                "order_sign.w" => $orderGoods['w'],
                "order_sign.status" => ['in',[$orderSignModel::STATUS_SIGN,$orderSignModel::STATUS_ADMIN_SIGN]]
            ];
            $signLog = $orderSignModel->getSignLog($signLogcondition,2);


        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("查询成功",$signLog);
    }


    /**
     * 学习记录详情
     *
     * @ApiMethod (POST)
     * @ApiWeigh (93)
     * @ApiParams   (name="id", type="string", required=true, description="成长总结id")
     */
    public function shouceInfo()
    {
        $id = $this->request->post('id');
        $orderSignModel = new OrderSign();
        try {
            $signLog = $orderSignModel->get($id);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("查询成功",$signLog);
    }
    /**
     * 学习记录修改
     *
     * @ApiMethod (POST)
     * @ApiWeigh (92)
     * @ApiParams   (name="id", type="string", required=true, description="成长总结id")
     * @ApiParams   (name="jilu_image", type="string", required=true, description="成长总结图片")
     * @ApiParams   (name="jilu_content", type="string", required=true, description="成长总结内容")
     */
    public function shouceChange()
    {

        $data = $this->request->post();
        $validate = new Validate([
            ["id","require","请选择学员成长总结"],
            ["jilu_image","require","请上传成长总结图片"],
//            ["jilu_content","require","请上传成长总结内容"],
        ]);
        $result = $validate->check($data);
        if(!$result){
            $this->error($validate->getError());
        }
        $orderSignModel = new OrderSign();
        try {
            $signLog = $orderSignModel->get($data['id']);
            $data['is_jilu'] = 1;
            $signLog->save($data);
        }catch (\Exception $exception){
            $this->error($exception->getMessage());
        }
        $this->success("填写成功");
    }

    /**
     * 请假列表
     * @ApiMethod   (POST)
     * @ApiWeigh (80)
     *
     */
    public function askLeaveList(){
        $orderSignModel = new OrderSign();
        Db::startTrans();
        try {
            $condition = [
                "order_sign.teacher_id" => $this->auth->id,
                "order_sign.status" => $orderSignModel::STATUS_LEAVE,
            ];
            $list = $orderSignModel->askSignList($condition);
            Db::commit();
        }catch (\Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success("查询成功",$list);
    }


}
